package projet.camping.sevlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import projet.camping.exception.ArgumentInvalideException;
import projet.camping.exception.PartieNonExistantException;
import projet.camping.usecases.GestionPartie;

@WebServlet(urlPatterns = "/rejoindrePartie.html")
public class RejoindrePartie extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB GestionPartie uccPartie;

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.sendRedirect(resp.encodeRedirectURL("campingBattle.jsp"));
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String partie = req.getParameter("nomPartie");
		HttpSession session = req.getSession(false);
		session.setAttribute("nomPartie", partie);
		
		if(session == null || (session!= null && session.getAttribute("login") == null)) {
			resp.sendRedirect(resp.encodeRedirectURL("campingBattle.jsp?fail"));
			return;
		}
		
		System.out.println(partie);
		System.out.println((String)session.getAttribute("login"));
		
		try {
			if(uccPartie.ajouterJoueur((String)session.getAttribute("login"), partie) == null){
				// la partie n'est plus disponible, redirection vers la page liste
				resp.sendRedirect(resp.encodeRedirectURL("campingBattle.jsp?fail"));
				return;
			}
		} catch (PartieNonExistantException e) {
			resp.sendRedirect(resp.encodeRedirectURL("listeParties.html?fail:partieNonExistante"));
			System.err.println("la partie n'existe pas");
			return;
		} catch (ArgumentInvalideException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		RequestDispatcher rd = getServletContext().getNamedDispatcher("Partie");
		
		rd.forward(req, resp);
	}
}
